//
//  NSObject+HDChatListManager.m
//  app
//
//  Created by D on 15/5/18.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDChatListManager.h"
#import "HDLoginUserURL.h"
#import "SNFmdbManager.h"

@interface HDChatListManager ()

@property (nonatomic,strong) JKHttpClient * jkHttp;
@property (nonatomic,strong) SNUniteUrl * uniteUrl;
@property (nonatomic,strong) NSMutableArray * mutableArray;
@property (nonatomic,strong) FMDatabaseQueue * fmdbQueue;
@property (nonatomic,strong) SNFmdbManager * snFmdbManager;
@property (nonatomic,strong) NSArray * dataArray;
@property (nonatomic,strong) NSString * isRefresh;
@property (nonatomic,strong) NSData * myData;
@property (nonatomic,strong) NSString * pmid;
@property (nonatomic,assign) BOOL includeChatList;
@property (nonatomic,assign) BOOL includeData;

@end

@implementation HDChatListManager

+(HDChatListManager *)shareManager
{
    AS_SINGLETON(HDChatListManager, manager,{
        manager = [[HDChatListManager alloc]init];
        manager.jkHttp = [[JKHttpClient alloc]init];
        manager.uniteUrl = [SNUniteUrl shareUniteUrl];
        manager.mutableArray = [NSMutableArray array];
        manager.dataArray = [NSArray array];
//        HDAppDelegate * delegate = (HDAppDelegate*)[UIApplication sharedApplication].delegate;
//        manager.fmdbQueue = delegate.fmdbQueue;
        manager.snFmdbManager = [SNFmdbManager shareManager];
        
        
                 })
    return manager;
}

-(void)loadChatListData:(HDChatListResult *)result Refresh:(NSString*)refresh
{
    self.isRefresh = refresh;
    
    if ([self.jkHttp isRunning]) {
        return;
    }
    [self.jkHttp get:self.uniteUrl.im_chatListUrl result:^(JKResponse *resp) {
        if (resp.OK) {
            result.success = YES;
            DLog(@"content = %@",resp.content);
            [self chatListDataSourceWithArray:resp.content[@"pmid_data"]];
        }else if (resp.failure){
            result.failure = YES;
        }
        [result invoke];
        
    }];
    
}
-(void)deleteChatListCell:(HDChatListResult*)result ChatPmid:(NSString*)pmid
{
    if ([self.jkHttp isRunning]) {
        return;
    }
    
    NSString * deleteUrl = [NSString stringWithFormat:@"%@%@",self.uniteUrl.im_deleteChatListUrl,pmid];
    [self.jkHttp get:deleteUrl result:^(JKResponse *resp) {
       
        if (resp.OK) {
            result.success = YES;
        }else if (result.failure){
            result.failure = YES;
        }
        [result invoke];
    }];
    
}







-(NSMutableArray*)chatListDataSourceWithArray:(NSArray*)array
{
    NSDate * date = [NSDate date];
    [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"chatLastRefreshTime"];
    
    [self.mutableArray removeAllObjects];
//    [self saveDataToDB: array];
    [self createFmdb];
    
    for (int i = 0 ; i < array.count; i++) {
        NSDictionary * dict = [array objectAtIndex:i];
        HDChatListModel * model = [HDChatListModel modelWithDict:dict];
        [self.mutableArray addObject:model];
        if (!model.pmid) {
            self.pmid = @"reply";
        }else
        {
            
            if (model.uid.integerValue == [[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue]) {
                self.pmid = model.fuid;
            }else
            {
                self.pmid = model.uid;
            }
        }
        if (self.isRefresh.integerValue == 0) {
            [self saveDataToDB: model Pmid:self.pmid OwnerAddId:[NSString stringWithFormat:@"%d",i]];
        }else
        {
            [self updataToDB:model Pmid:self.pmid OwnerAddId:[NSString stringWithFormat:@"%d",i]];
        }
    }
    
    
    return self.mutableArray;
}

#pragma mark - 更新插入
-(void)updataToDBWithDic:(NSDictionary*)dic
{
//    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
//        
//        NSString * sql = [NSString string];
//        
//        if ([[dic objectForKey:@"uid"]integerValue] == [[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue]) {
//            sql = [NSString stringWithFormat:@"UPDATE ChatList SET pmid = '%@', name = '%@',face = '%@',lastTalk = '%@',time = '%@',uid = '%@',msgid = '%@',omit = '%@',omitid = '%@', delSign = '%@', WHERE pmid = '%@' ",[dic objectForKey:@"pmid"],[dic objectForKey:@"name"],[dic objectForKey:@"face"],[dic objectForKey:@"lastTalk"],[dic objectForKey:@"time"],[dic objectForKey:@"uid"],[dic objectForKey:@"msgid"],[dic objectForKey:@"omit"],[dic objectForKey:@"omitid"],[dic objectForKey:@"delSign"],[dic objectForKey:@"pmid"]];
//        }else{
//            sql = [NSString stringWithFormat:@"UPDATE ChatList SET pmid = '%@', name = '%@',face = '%@',lastTalk = '%@',time = '%@',uid = '%@',msgid = '%@',omit = '%@',omitid = '%@' , delSign = '%@' WHERE pmid = '%@' ",[dic objectForKey:@"pmid"],[dic objectForKey:@"name"],[dic objectForKey:@"face"],[dic objectForKey:@"lastTalk"],[dic objectForKey:@"time"],[dic objectForKey:@"uid"],[dic objectForKey:@"msgid"],[dic objectForKey:@"omit"],[dic objectForKey:@"omitid"],[dic objectForKey:@"delSign"],[dic objectForKey:@"pmid"]];
//            
//        }
//        
//        
//        if ([db executeUpdate:sql ]) {
//            DLog(@"更新成功到ChatList表中");
//        }
////        [db close];
//    }];
////    [self.fmdbQueue close];
    
    NSString * sql = [NSString string];
    
    if ([[dic objectForKey:@"uid"]integerValue] == [[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue]) {
        sql = [NSString stringWithFormat:@"UPDATE ChatList_%@ SET pmid = '%@', name = '%@',face = '%@',lastTalk = '%@',time = '%@',uid = '%@',msgid = '%@',omit = '%@',omitid = '%@', delSign = '%@', WHERE pmid = '%@' ",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],[dic objectForKey:@"pmid"],[dic objectForKey:@"name"],[dic objectForKey:@"face"],[dic objectForKey:@"lastTalk"],[dic objectForKey:@"time"],[dic objectForKey:@"uid"],[dic objectForKey:@"msgid"],[dic objectForKey:@"omit"],[dic objectForKey:@"omitid"],[dic objectForKey:@"delSign"],[dic objectForKey:@"pmid"]];
    }else{
        sql = [NSString stringWithFormat:@"UPDATE ChatList_%@ SET pmid = '%@', name = '%@',face = '%@',lastTalk = '%@',time = '%@',uid = '%@',msgid = '%@',omit = '%@',omitid = '%@' , delSign = '%@' WHERE pmid = '%@' ",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],[dic objectForKey:@"pmid"],[dic objectForKey:@"name"],[dic objectForKey:@"face"],[dic objectForKey:@"lastTalk"],[dic objectForKey:@"time"],[dic objectForKey:@"uid"],[dic objectForKey:@"msgid"],[dic objectForKey:@"omit"],[dic objectForKey:@"omitid"],[dic objectForKey:@"delSign"],[dic objectForKey:@"pmid"]];
        
    }
    [self.snFmdbManager performExecuteUpdateWithSql:sql];
    

}

#pragma mark - 更新数据库
-(void)updataToDB:(HDChatListModel*)model Pmid:(NSString *)pmid OwnerAddId:(NSString*)ownerAddid
{
//
//    NSString * sql = [NSString string];
//    
//    if (model.uid.integerValue == [[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue]) {
//        sql = [NSString stringWithFormat:@"UPDATE ChatList SET pmid = '%@', name = '%@',face = '%@',lastTalk = '%@',time = '%@',ownerAddId = '%@',msgid = '%@',omit = '%@', delSign = '%@', WHERE uid = '%@' ",pmid,model.f_name,model.f_face,model.lastTalk,model.time,ownerAddid,model.msgid,@"0",model.delSign,pmid];
//    }else{
//        sql = [NSString stringWithFormat:@"UPDATE ChatList SET pmid = '%@', name = '%@',face = '%@',lastTalk = '%@',time = '%@',ownerAddId = '%@',msgid = '%@',omit = '%@' , delSign = '%@', WHERE uid = '%@' ",pmid,model.name,model.face,model.lastTalk,model.time,ownerAddid,model.msgid,@"0",model.delSign,pmid];
//        
//    }
//    [self.snFmdbManager performExecuteUpdateWithSql:sql];
//    
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        NSString * sql = [NSString string];
        
        if (model.uid.integerValue == [[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue]) {
            sql = [NSString stringWithFormat:@"UPDATE ChatList_%@ SET pmid = '%@', name = '%@',face = '%@',lastTalk = '%@',time = '%@',ownerAddId = '%@',msgid = '%@',omit = '%@', delSign = '%@' WHERE uid = '%@' ",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],pmid,model.f_name,model.f_face,model.lastTalk,model.time,ownerAddid,model.msgid,@"0",model.delSign,pmid];
        }else{
            sql = [NSString stringWithFormat:@"UPDATE ChatList_%@ SET pmid = '%@', name = '%@',face = '%@',lastTalk = '%@',time = '%@',ownerAddId = '%@',msgid = '%@',omit = '%@' , delSign = '%@' WHERE uid = '%@' ",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],pmid,model.name,model.face,model.lastTalk,model.time,ownerAddid,model.msgid,@"0",model.delSign,pmid];
            
        }
        
        if ([db executeUpdate:sql]) {
            DLog(@"更新ChatList表成功");
        }
        
    }];
    
    

}

#pragma mark - 保存到数据库
-(void)saveDataToDB:(HDChatListModel*)model Pmid:(NSString*)pmid OwnerAddId:(NSString*)ownerAddid
{

    
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        NSString * sql = [NSString stringWithFormat:@"insert into ChatList_%@(uid ,pmid,name,face, lastTalk,time, ownerAddId,msgid,omit, omitid,delSign) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]] ;
        if (model.uid.integerValue == [[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue]) {
            self.dataArray = @[pmid,model.pmid,model.f_name,model.f_face,model.lastTalk,model.time,ownerAddid,model.msgid,@"0",model.msgid,model.delSign];
        }else
        {
            self.dataArray = @[pmid,model.pmid,model.name,model.face,model.lastTalk,model.time,ownerAddid,model.msgid,@"0",model.msgid,model.delSign];
        }
        if ([db executeUpdate:sql withArgumentsInArray:self.dataArray]) {
            DLog(@"保存到了 ChatList表");
        }
    }];
    
    
}
#pragma mark - 插入数据库
-(void)saveToFmdbWithDic:(NSArray*)array
{
   
//    
//    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
//        NSString * sql = @"insert into ChatList(pmid, name, face, lastTalk, time, uid, msgid, omit, omitid,delSign) values (?, ?, ?, ?, ?, ?, ?, ?, ?,?);";
//        if ([db executeUpdate:sql withArgumentsInArray:array]) {
//            DLog(@"保存成功到ChatList表中");
//        }
////        [db close];
//    }];
////    [self.fmdbQueue close];
    
    NSString * sql = [NSString stringWithFormat:@"insert into ChatList_%@(uid ,pmid,name,face, lastTalk,time, ownerAddId,msgid,omit, omitid,delSign) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]] ;
    [self.snFmdbManager performExecuteUpdateWithSql:sql withArguments:array];
}
#pragma mark - 删除更新
-(void)updataAndDeleteToDB:(NSString*)pmid
{
//    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
//        
//        NSString * sql = [NSString stringWithFormat:@"UPDATE ChatList SET delSign = '%@' WHERE pmid = '%@' ",@"111",pmid];
//        
//        if ([db executeUpdate:sql ]) {
//            DLog(@"更新成功到Chatuid表中");
//        }
////        [db close];
//    }];
////    [self.fmdbQueue close];
    NSString * sql = [NSString stringWithFormat:@"UPDATE ChatList_%@ SET delSign = '%@' WHERE uid = '%@' ",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],@"111",pmid];
    [self.snFmdbManager performExecuteUpdateWithSql:sql];
}
#pragma mark - 删除某条数据
-(void)deleteDataToDB:(NSString *)pmid
{
//    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
//        NSString * sql = @"DELETE FROM ChatList WHERE pmid = ?;";
//        if ([db executeUpdate:sql,pmid]) {
//            DLog(@"删除成功");
//        }
////        [db close];
//    }];
////    [self.fmdbQueue close];
    NSString * sql = [NSString stringWithFormat:@"DELETE FROM ChatList_%@ WHERE pmid = ?;",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]] ;
    NSArray * array = @[pmid];
    [self.snFmdbManager performExecuteUpdateWithSql:sql withArguments:array];
}

#pragma mark - 创建表
- (void)createFmdb
{

     NSString * sql_cList = [NSString stringWithFormat:@"create table if not exists ChatList_%@(uid TEXT PRIMARY KEY ,pmid TEXT,name TEXT ,face TEXT, lastTalk TEXT,time TEXT, ownerAddId TEXT,msgid TEXT,omit TEXT, omitid TEXT,delSign TEXT);",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]] ;
    [self.snFmdbManager createTableWithSql:sql_cList];
    
}

#pragma mark - 从数据库中读取数据
- (NSMutableArray *)arrayFromFmdb
{
//    NSMutableArray * arr1 = [NSMutableArray array];
    NSMutableArray * arr2 = [NSMutableArray array];
//
//    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
//        FMResultSet * set_one = [db executeQuery:@"select * from sqlite_master where name  = 'ChatList';"] ;
//        if ([set_one next]){
//            NSString * sql = @"select * from ChatList;";
//            FMResultSet * set = [db executeQuery:sql];
//            [self.mutableArray removeAllObjects];
//            while ([set next]) {
//  
//                NSString * pmid = [set stringForColumn:@"pmid"];
//                NSString * name = [set stringForColumn:@"name"];
//                NSString * face = [set stringForColumn:@"face"];
//                NSString * uid = [set stringForColumn:@"uid"];
//                NSString * lastTalk = [[NSString alloc]init];
//                NSString * reply = [NSString stringWithFormat:@"reply%@",uid];
//                if ([pmid isEqualToString:reply]) {
//                    lastTalk = [NSString stringWithFormat:@"%@回复了您的帖子",name];
//                }else
//                {
//                    lastTalk = [set stringForColumn:@"lastTalk"];
//                }
//                NSString * time = [set stringForColumn:@"time"];
//                NSString * msgid = [set stringForColumn:@"msgid"];
//                NSString * delSign = [set stringForColumn:@"delSign"];
//                
//                NSDictionary * dict = @{@"pmid":pmid,
//                                        @"face":face,
//                                        @"nickname":name,
//                                        @"dateline":time,
//                                        @"content":lastTalk,
//                                        @"uid":uid,
//                                        @"msgid":msgid,
//                                        @"delSign":delSign};
//                
////                [arr1 addObject:[HDChatListModel modelWithDict:dict]];
//                [arr1 addObject:dict];
//            }
//            [set close];
//        }
//        [set_one close];
////        [db close];
//    }];
////    [self.fmdbQueue close];
    
    [arr2 addObjectsFromArray:[self.snFmdbManager arrayFromFmdbWithArray:self.mutableArray]];
    for (int i = 0 ; i < arr2.count; i ++) {
        DLog(@"排序前--> %@",[[arr2 objectAtIndex:i]objectForKey:@"dateline" ] );
        
    }
    
    NSSortDescriptor*sorter=[[NSSortDescriptor alloc]initWithKey:@"dateline" ascending:NO];
    NSMutableArray *sortDescriptors=[[NSMutableArray alloc]initWithObjects:&sorter count:1];
    NSArray *sortArray=[arr2 sortedArrayUsingDescriptors:sortDescriptors];
    
    for (int i=0; i<[sortArray count]; i++) {
        NSLog(@"排序后----->>%@",[[sortArray objectAtIndex:i] objectForKey:@"dateline"]);
        if ([[[sortArray objectAtIndex:i] objectForKey:@"delSign"]integerValue] == 000) {
           [self.mutableArray addObject:[HDChatListModel modelWithDict:[sortArray objectAtIndex:i]]];
        }
        
    }
    
    return self.mutableArray;
}
#pragma mark - 表是否存在
- (BOOL)fmdbIncludeChatList
{
    NSString * tablename = [NSString stringWithFormat:@"ChatList_%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
    return [self.snFmdbManager fmdbIncludetableWithTableName:tablename];
}

#pragma mark - 表中是否存有数据
- (BOOL)fmdbIncludeData
{
     NSString * tablename = [NSString stringWithFormat:@"ChatList_%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
    return [self.snFmdbManager tabelIncludeDataWithTableName:tablename];
}


#pragma mark - 是否自动刷新数据
- (BOOL)shouldRefreshChatListData
{
    NSFileManager * fm = [NSFileManager defaultManager];
    
    if ([fm fileExistsAtPath:kDBPath]) {//数据库文件已经存在
        //判断表是不是存在:
        if ([self fmdbIncludeChatList]) {//表是存在的
            //通过时间判断是否需要自动刷新
            NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
            NSDate * participationLastRefreshTime = [ud objectForKey:@"chatLastRefreshTime"];
            NSDate * nowDate = [NSDate date];
            DLog(@"chatLastRefreshTime ==== %@",participationLastRefreshTime);
            NSTimeInterval aTimer = [nowDate timeIntervalSinceDate:participationLastRefreshTime];
            DLog(@"chatLast时间差  ===== %f",aTimer);
            if (aTimer > REFRESHSELFTIME) {//已经有一段时间没有刷新了,需要自动刷新
                DLog(@"chatLast需要自动刷新");
                return YES;
            } else {//不需要自动刷新
                DLog(@"chatLast不需要自动刷新");
                return NO;
            }
        } else {//表不存在,第一次进入此页面
            return YES;
        }
    } else {//数据库文件都不存在,第一次进入这个页面
        return YES;
    }
}

@end














